<template>
  <div style="text-align: center; margin: 0 20px">
    <div style="margin-top: 150px">
      <div style="font-size: 25px; font-weight: bold">登录</div>
      <div style="font-size: 14px; color: rgb(128, 128, 128)">
        在进入系统之前请先入用户名和密码进行登录
      </div>
    </div>

    <div style="margin-top: 50px">
      <el-input v-model="form.username" type="text" placeholder="用户名/邮箱">
        <template #prefix>
          <el-icon><User /></el-icon>
        </template>
      </el-input>

      <el-input v-model="form.password" type="password" style="margin-top: 10px" placeholder="密码">
        <template #prefix>
          <el-icon><Lock /></el-icon>
        </template>
      </el-input>
    </div>

    <div style="margin-top: 10px">
      <el-row>
        <el-col :span="12">
          <el-checkbox v-model="form.remember" label="记住我"></el-checkbox>
        </el-col>
        <el-col :span="12">
          <el-link @click="router.push('/forger')">忘记密码？</el-link>
        </el-col>
      </el-row>
    </div>

    <div>
      <el-button style="width: 270px" type="success" @click="login()">立即登录</el-button>
    </div>
    <el-divider>
      <span style="color: rgb(128, 128, 128); font-size: 13px">没有账号</span>
    </el-divider>
    <div>
      <el-button style="width: 270px" type="warning" plain @click="router.push('/register')"
        >注册账号</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { Lock, User } from '@element-plus/icons-vue'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/net'
import router from '@/router'
import { useStore } from '@/stores/counter'

const store = useStore()

const form = reactive({
  username: '',
  password: '',
  remember: false
})

const login = () => {
  if (!form.username || !form.password) {
    ElMessage.warning('请填写用户名和密码')
  } else {
    post(
      '/api/auth/login',
      {
        username: form.username,
        password: form.password,
        remember: form.remember
      },
      (message) => {
        ElMessage.success(message)
        get(
          '/api/user/me',
          (data) => {
            store.auth.useStore = data
            router.push('/index')
          },
          () => {
            store.auth.useStore = null
          }
        )
      }
    )
  }
}
</script>

<style scoped></style>
